package cn.cleanarch.infra.idp.pms.controller;

import cn.cleanarch.infra.idp.commons.domain.dto.PageResult;
import cn.cleanarch.infra.idp.pms.domain.dto.DesignFileDTO;
import cn.cleanarch.infra.idp.pms.domain.dto.DesignFileTagDTO;
import cn.cleanarch.infra.idp.pms.domain.dto.FileTypeOptionDTO;
import cn.cleanarch.infra.idp.pms.domain.entity.DesignFile;
import cn.cleanarch.infra.idp.pms.domain.query.DesignFileQuery;
import cn.cleanarch.infra.idp.pms.service.DesignFileService;
import cn.cleanarch.infra.idp.web.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import cn.cleanarch.infra.idp.pms.constants.ApiPathConstants;
import cn.cleanarch.infra.idp.pms.constants.ContentTypeConstants;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 设计文件管理控制器
 */
@RestController
@RequestMapping("/pms/design-file")
public class DesignFileController {

    private static final Logger logger = LoggerFactory.getLogger(DesignFileController.class);

    @Autowired
    private DesignFileService designFileService;

    /**
     * 分页查询设计文件
     */
    @GetMapping
    public Result pageQuery(DesignFileQuery query) {
        PageResult<DesignFileDTO> result = designFileService.pageQuery(query);
        return Result.data(result);
    }

    /**
     * 根据ID获取设计文件
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Long id) {
        DesignFile designFile = designFileService.getById(id);
        // 将实体类转换为DTO，避免Java 8时间类型的序列化问题
        DesignFileDTO designFileDTO = designFileService.convertToDTO(designFile);
        return Result.data(designFileDTO);
    }

    /**
     * 创建设计文件
     */
    @PostMapping
    public Result create(@RequestBody DesignFileDTO dto) {
        // 将DTO转换为实体类
        DesignFile designFile = convertToEntity(dto);
        designFileService.create(designFile);
        DesignFileDTO resultDTO = designFileService.convertToDTO(designFile);
        return Result.data(resultDTO);
    }

    /**
     * 更新设计文件
     */
    @PutMapping
    public Result update(@RequestBody DesignFileDTO dto) {
        // 将DTO转换为实体类
        DesignFile designFile = convertToEntity(dto);
        // 更新需要赋值 ID
        designFile.setId(dto.getId());
        designFileService.update(designFile);
        DesignFileDTO resultDTO = designFileService.convertToDTO(designFile);
        return Result.data(resultDTO);
    }

    /**
     * 删除设计文件
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id) {
        designFileService.delete(id);
        return Result.success();
    }

    /**
     * 获取标签列表
     */
    @GetMapping("/tags")
    public Result getTags() {
        List<DesignFileTagDTO> tags = designFileService.getTags();
        return Result.data(tags);
    }

    /**
     * 创建设计文件标签
     */
    @PostMapping("/tags")
    public Result createTag(@RequestBody DesignFileTagDTO dto) {
        DesignFileTagDTO result = designFileService.createTag(dto);
        return Result.data(result);
    }

    /**
     * 更新设计文件标签
     */
    @PutMapping("/tags/{id}")
    public Result updateTag(@PathVariable("id") Long id, @RequestBody DesignFileTagDTO dto) {
        dto.setId(id);
        DesignFileTagDTO result = designFileService.updateTag(dto);
        return Result.data(result);
    }

    /**
     * 删除设计文件标签
     */
    @DeleteMapping("/tags/{id}")
    public Result deleteTag(@PathVariable("id") Long id) {
        designFileService.deleteTag(id);
        return Result.success();
    }

    /**
     * 获取文件类型选项
     */
    @GetMapping("/file-types")
    public Result getFileTypeOptions() {
        List<FileTypeOptionDTO> options = designFileService.getFileTypeOptions();
        return Result.data(options);
    }

    /**
     * 安全扫描文件
     */
    @PostMapping("/{id}/scan")
    public Result scanFileSecurity(@PathVariable("id") Long id) {
        designFileService.scanFileSecurity(id);
        return Result.success();
    }

    /**
     * 仅上传文件（不包含业务信息，后续可更新）
     */
    @PostMapping("/upload-only")
    public Result uploadFileOnly(@RequestParam("file") MultipartFile file) {
        try {
            DesignFileDTO result = designFileService.uploadFileOnly(file);
            return Result.data(result);
        } catch (Exception e) {
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/{id}/download")
    public Result downloadFile(@PathVariable("id") Long id) {
        try {
            String downloadUrl = designFileService.getFileDownloadUrl(id);
            return Result.data(downloadUrl);
        } catch (Exception e) {
            return Result.fail("文件下载失败: " + e.getMessage());
        }
    }

    /**
     * 批量上传文件
     */
    @PostMapping("/upload/batch")
    public Result uploadFilesBatch(@RequestParam("files") MultipartFile[] files) {
        try {
            List<DesignFileDTO> results = designFileService.uploadFilesBatch(files);
            return Result.data(results);
        } catch (Exception e) {
            return Result.fail("批量文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 将DTO转换为实体类
     */
    private DesignFile convertToEntity(DesignFileDTO dto) {
        if (dto == null) {
            return null;
        }

        DesignFile entity = new DesignFile();
        // 设置基本字段
        entity.setName(dto.getName());
        entity.setDescription(dto.getDescription());
        entity.setFileType(dto.getFileType());
        entity.setFileSize(dto.getFileSize());
        entity.setTags(dto.getTags());
        entity.setProjectId(dto.getProjectId());
        entity.setCreatedBy(dto.getCreatedBy());
        entity.setUpdatedBy(dto.getUpdatedBy());

        // 设置其他必要字段
        entity.setFileKey(dto.getFileKey());
        entity.setFileMd5(dto.getFileMd5());
        entity.setVersion(dto.getVersion());
        entity.setStatus(dto.getStatus());
        entity.setOwnerId(dto.getOwnerId());

        // 正确处理时间字段转换
        if (dto.getLastAccessTime() != null) {
            // 将 LocalDateTime 转换为 Long 时间戳
            entity.setLastAccessTime(dto.getLastAccessTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
        }

        if (dto.getDeletedAt() != null) {
            // 将 LocalDateTime 转换为 Long 时间戳
            entity.setDeletedAt(dto.getDeletedAt().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
        }

        // 设置默认状态
        if (entity.getStatus() == null) {
            entity.setStatus("NORMAL");
        }
        if (entity.getUsedStatus() == null) {
            entity.setUsedStatus("UNUSED");
        }
        if (entity.getSecurityStatus() == null) {
            entity.setSecurityStatus("UNSCANNED");
        }

        return entity;
    }
}
